import "./reset.css";
import dayjs from "dayjs";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import croppingUpload from "../upload.vue";
import userAvatar from "@/assets/user.jpg";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import { getToken } from "@/utils/auth";
import {
  getKeyList,
  isAllEmpty,
  hideTextAtIndex,
  deviceDetection
} from "@pureadmin/utils";
import {
  getRoleIds,
  getDeptList,
  getUserList,
  getAllRoleList,
  addUser,
  updateUser,
  deleteUser,
  updateUserStatus,
  uploadFile,
  updateUserAvatar,
  resetPassword,
  assignRoleToUser
} from "@/api/system";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";
import { cloneDeep } from "@pureadmin/utils";
import Axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type CustomParamsSerializer
} from "axios";
const { VITE_GLOBAL_API_URL } = import.meta.env;
import { hasAuth, hasAuths } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import {
  startSignalRConnection,
  subscribeToReceiveMessage,
  sendMessage,
  unsubscribeFromMessage,
  disconnectSignalR
} from "@/utils/signalRService";

export function useUser(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    // 左侧组织机构树的id
    organizationId: null,
    userName: "",
    phoneNumber: "",
    isActive: null,
    pageNumber: 1,
    pageSize: 10,
    orderBy: "Id",
    sortDirection: "Descending"
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // 上传头像信息
  const avatarInfo = ref();
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const higherDeptOptions = ref();
  const deptData = ref([]);
  const treeData = ref([]);
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "用户编号",
      prop: "userId",
      width: 90
    },
    {
      label: "用户头像",
      prop: "profilePictureDataUrl",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.profilePictureDataUrl || userAvatar}
          preview-src-list={Array.of(row.profilePictureDataUrl || userAvatar)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "用户账号",
      prop: "userName",
      minWidth: 130
    },
    {
      label: "用户昵称",
      prop: "nickname",
      minWidth: 130
    },
    {
      label: "性别",
      prop: "genderType",
      minWidth: 90,
      cellRenderer: ({ row, props }) => (
        <el-tag
          size={props.size}
          type={getTagType(row.genderType)}
          effect="plain"
        >
          {getGenderText(row.genderType)}
        </el-tag>
      )
    },
    {
      label: "组织机构",
      prop: "organizationName",
      minWidth: 90
    },
    {
      label: "手机号码",
      prop: "phoneNumber",
      minWidth: 90,
      formatter: ({ phoneNumber }) => {
        if (phoneNumber) {
          return hideTextAtIndex(phoneNumber, { start: 3, end: 6 });
        } else {
          return phoneNumber;
        }
      }
    },
    {
      label: "状态",
      prop: "isActive",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          disabled={!hasAuth("user:userid:status")}
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.isActive}
          active-value={true}
          inactive-value={false}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "created",
      formatter: ({ created }) => dayjs(created).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation",
      hide: !hasAuths(["user:id", "user:delete:ids"])
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.isActive === true ? "启用" : "停用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.userName
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(async () => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          await updateUserStatus({
            userId: row.userId,
            concurrencyStamp: row.concurrencyStamp
          })
            .then(() => {
              message("修改成功", {
                type: "success"
              });
            })
            .catch(() => {})
            .finally(async () => {
              await onSearch();
            });
        }, 10);
      })
      .catch(async () => {
        row.isActive === false ? (row.isActive = true) : (row.isActive = false);
      });
  }

  interface TreeNode {
    id: string;
    organizationId: string;
    organizationName: string;
    organizationPrincipalId: string | null;
    phoneNumber: string;
    email: string;
    sort: number;
    description: string;
    isActive: boolean;
    parentId: string | null;
    created: string;
    concurrencyStamp: string;
    children?: TreeNode[];
    level: number; // 新增的节点等级属性
  }

  function buildTree(organizations: TreeNode[]): TreeNode[] {
    const map: { [key: string]: TreeNode } = {};
    const tree: TreeNode[] = [];

    organizations.forEach(organization => {
      map[organization.id] = organization;
      organization.children = [];
    });

    organizations.forEach(organization => {
      if (organization.parentId !== null && map[organization.parentId]) {
        const parentLevel = map[organization.parentId].level || 0;
        organization.level = parentLevel + 1;
        map[organization.parentId].children.push(organization);
      } else {
        organization.level = 0;
        tree.push(organization);
      }
    });
    return tree;
  }

  function handleUpdate(row) {
    console.log(row);
  }

  async function handleDelete(row) {
    await deleteUser({ userIds: row.userId });
    message(`删除成功`, { type: "success" });
    onSearch();
  }

  async function handleSizeChange(val: number) {
    form.pageSize = val;
    await onSearch();
  }

  async function handleCurrentChange(val: number) {
    form.pageNumber = val;
    await onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  async function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const deleteUserIds = getKeyList(curSelected, "id");
    await deleteUser({ userIds: deleteUserIds });
    message(`已删除用户编号为 ${deleteUserIds} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getUserList(toRaw(form));
    dataList.value = data.items;
    pagination.total = data.totalItems;
    //pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;

    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.organizationId = null;
    treeRef.value.onTreeReset();
    onSearch();
  };

  function onTreeSelect({ id, selected }) {
    form.organizationId = selected ? id : "";
    onSearch();
  }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          title,
          higherDeptOptions: buildTree(cloneDeep(deptData.value)),
          userId: row?.userId ?? 0,
          userName: row?.userName ?? "",
          phoneNumber: row?.phoneNumber ?? "",
          nickname: row?.nickname ?? "",
          realname: row?.realname ?? "",
          password: row?.confirmPassword ?? "",
          confirmPassword: row?.confirmPassword ?? "",
          email: row?.email ?? "",
          genderType: row?.genderType ?? "Secrecy",
          organizationId: row?.organizationId ?? "",
          isActive: row?.isActive ?? false,
          signature: row?.signature ?? "",
          concurrencyStamp: row?.concurrencyStamp ?? ""
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            curData.organizationId =
              curData.organizationId === "" ? null : curData.organizationId;
            // 表单规则校验通过
            if (title === "新增") {
              await addUser(curData);
              // 实际开发先调用新增接口，再进行下面操作
              chores();
            } else {
              await updateUser(curData);
              // 实际开发先调用修改接口，再进行下面操作
              chores();
            }
          }
        });
      }
    });
  }

  const cropRef = ref();
  /** 上传头像 */
  function handleUpload(row) {
    addDialog({
      title: "裁剪、上传头像",
      width: "40%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () =>
        h(croppingUpload, {
          ref: cropRef,
          imgSrc: row.profilePictureDataUrl || userAvatar,
          onCropper: info => (avatarInfo.value = info)
        }),
      beforeSure: async done => {
        const formData = new FormData();
        formData.append("file", avatarInfo.value.blob);

        const { accessToken } = getToken();

        // 发送 POST 请求
        Axios.post(`${VITE_GLOBAL_API_URL}api/upload/file/avatar`, formData, {
          headers: {
            "Content-Type": "multipart/form-data", // 设置请求头，必须设置为 multipart/form-data
            Authorization: `Bearer ${accessToken}` // 添加Bearer令牌授权
          }
        })
          .then(async response => {
            // 上传成功，处理服务器返回的响应数据
            if (response.data.success) {
              await updateUserAvatar({
                userId: row.userId,
                profilePictureDataUrl: response.data.data.src,
                concurrencyStamp: row.concurrencyStamp
              });
              if (row.userName === useUserStoreHook().username) {
                useUserStoreHook().SET_ISREFRESHTOKEN(true);
              }
              message(`上传成功`, {
                type: "success"
              });

              await onSearch(); // 刷新表格数据
            }
          })
          .catch(error => {
            // 上传失败，处理错误
            message(`上传失败`, {
              type: "error"
            });
          });
        // 根据实际业务使用avatarInfo.value和row里的某些字段去调用上传头像接口即可
        done(); // 关闭弹框
      },
      closeCallBack: () => cropRef.value.hidePopover()
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    addDialog({
      title: `重置 ${row.userName} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(async valid => {
          if (valid) {
            await resetPassword({
              userId: row?.userId,
              password: pwdForm.newPwd,
              concurrencyStamp: row?.concurrencyStamp
            });
            // 表单规则校验通过
            message(`已成功重置 ${row.userName} 用户的密码`, {
              type: "success"
            });

            onSearch(); // 刷新表格数据
            done(); // 关闭弹框
          }
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row) {
    // 选中的角色列表
    const roleIdsResponse =
      (await getRoleIds({ userId: row.userId })).data ?? [];
    const roleIds = roleIdsResponse.map(role => role.roleId);
    addDialog({
      title: `分配 ${row.userName} 用户的角色`,
      props: {
        formInline: {
          userName: row?.userName ?? "",
          nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          roleIds
        }
      },
      width: "400px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm),
      beforeSure: async (done, { options }) => {
        const curData = options.props.formInline as RoleFormItemProps;
        await assignRoleToUser({
          userIds: row.userId,
          roleIds: curData.roleIds.join()
        });
        message(`分配成功`, {
          type: "success"
        });
        // 根据实际业务使用curData.ids和row里的某些字段去调用修改角色接口即可
        done(); // 关闭弹框
      }
    });
  }

  // 获取标签类型
  function getTagType(genderType) {
    if (genderType === "Male") {
      return "success"; // 男性标签类型为 success
    } else if (genderType === "Female") {
      return "danger"; // 女性标签类型为 danger
    } else {
      return "info"; // 其他情况（如保密）标签类型为 info
    }
  }
  // 获取性别文本内容
  function getGenderText(genderType) {
    if (genderType === "Female") {
      return "女";
    } else if (genderType === "Male") {
      return "男";
    } else {
      return "保密";
    }
  }

  onMounted(async () => {
    treeLoading.value = true;
    onSearch();

    // 归属组织机构
    const { data } = await getDeptList();
    deptData.value = data;
    higherDeptOptions.value = buildTree(data);
    treeData.value = buildTree(data);
    treeLoading.value = false;

    // 角色列表
    roleOptions.value = (await getAllRoleList()).data;
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    onTreeSelect,
    handleUpdate,
    handleDelete,
    handleUpload,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
